﻿using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using Components;

namespace WorkflowDesigner
{
    public class WorkflowFALC
    {
        /// <summary>
        /// return file name
        /// </summary>
        public static void SaveWorkflow(WorkflowDesign wfDesign)
        {
            using (IsolatedStorageFile isf=IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(wfDesign.FileName, System.IO.FileMode.Create, isf))
                {
                    using (XmlWriter writer = XmlWriter.Create(isfs))
                    {
                        XDocument xDoc = wfDesign.Save();
                        xDoc.Save(writer);
                        writer.Flush();
                        writer.Close();
                    }
                }
            }
        }

        public static List<string> ListWorkflows()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                List<string> workflowNames=new List<string>();
                string[] fileNames = isf.GetFileNames("*.wox");
                if(fileNames !=null && fileNames.Length>0)
                {
                    foreach(string fileName in fileNames)
                    {
                        string workflowName = fileName;
                        if (workflowName.EndsWith(".wox"))
                            workflowName = workflowName.Substring(0, workflowName.Length - ".wox".Length);
                        workflowNames.Add(workflowName);
                    }
                }
                return workflowNames;
            }
        }

        public static XDocument ReadWorkflow(string workflowName)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string fileName = workflowName + ".wox";
                if (!isf.FileExists(fileName))
                    return null;
                XDocument xDoc = null;
                using (
                    IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(
                        fileName, System.IO.FileMode.Open, isf))
                {
                    xDoc = XDocument.Load(isfs);
                }
                return xDoc;
            }
        }
    }
}
